/*
 * @Author: c
 * @Date: 2024-01-05 22:20:29
 * @LastEditTime: 2024-01-05 22:20:37
 * @LastEditors: c
 * @Description: 
 * @FilePath: \music-web-backend\src\common\service\bcrypt.service.ts
 * https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// Copyright 2024 Administrator
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import { Injectable } from '@nestjs/common'
import * as bcrypt from 'bcryptjs'

@Injectable()
export class BcryptService {
  /**
   * 用于哈希密码的盐
   */ 
  private static readonly SALT_ROUNDS: number = 10
  /**
   * 对比检查密码
   * @param { string } rawStr 要比较的数据, 使用登录时传递过来的密码
   * @param { string } hashedStr 要比较的数据, 使用从数据库中查询出来的加密过的密码
   */
  static async compare(rawStr: string, hashedStr: string) {
    return bcrypt.compareSync(rawStr, hashedStr)
  }
  /**
   * 生成 hash
   * @param { string } rawStr 要加密的数据
   * @param { string } salt 用于哈希密码的盐。如果指定为数字，则将使用指定的轮数生成盐并将其使用。推荐 10
   */
  static async hash(rawStr: string, salt?: string) {
    return bcrypt.hashSync(rawStr, salt || BcryptService.SALT_ROUNDS)
  }
}